<?php
use think\Db;
function returnJson($code,$msg,$data=null){
	if(!isset($data)){
		return json(['code'=>$code,'msg'=>$msg]);
	}
    return json(['code'=>$code,'msg'=>$msg,'data'=>$data]);
}

//多个数组的排列组合
/*  $b = array(1,2,3);
	$a=array(1,2,3);
	$e=array(1,2,3,4,5);
	$d = array($a,$b,$e);是一维数组变成二维数组*/
function array_zuhe($d){
	$len = 1;
	$arrLen = count($d); //需要排列数组有多少个

	$recIndex = null; //记录当前该取的位置
	//foreach 计数
	$count_3 = 0;
	foreach ($d as $key => $value) {
		$lenRec[$count_3] = count($value);
		$len = $lenRec[$count_3]*$len;
		$recIndex[] = 0;//第一次全部取第0个
		$count_3++;
	}
	//算出% 的值
	$count = 1;
	foreach ($lenRec as $key => $value) {
		$moduloVal = 1;
		if($arrLen == $count){
		$modulo[] = count($d[$arrLen-1]); //等于最后一个的长度
		}else{
			$count_1 = 1;
			foreach ($lenRec as $index => $item) {
				$count_1 > $count && $moduloVal = $moduloVal*$item;
				$count_1 ++;
			}
			$modulo[] = $moduloVal;
		}
		$count ++;//为了防止$d key是有值的 不是自然序列 需要计数
	}
	$i = 1;
	static $a_name=0;
	while ( $i <= $len) {
		$html = '';
		$count_2 = 0;// 取模
		$temp = '';
		foreach ($d as $value) {
			$html .= $value[$recIndex[$count_2]%$lenRec[$count_2]].",";
			$count_2 ++;
		}
		$res[$a_name]=mb_substr($html,0,-1);
		foreach ($modulo as $key => $value) {
			if($i%$value == 0 && $key < $arrLen - 1 ){
			$recIndex[$key] = $recIndex[$key] +1;
			}
			if($key == $arrLen - 1){
				if($i%$value == 0){
				$recIndex[$key] = 0;
				}else{
				$recIndex[$key] = $recIndex[$key] +1;
				}
			}
		}
		$i ++;
		$a_name++;
	//改变获取的位置
	}
	return $res;
}

//根据属性id组合获规格和属性的拼接数据
//$attr_ids 数属性id的组合，如3,4
function getAttrs1($attr_ids){
    $attr_ids=explode(',',$attr_ids);
    $attrs=[];
    foreach ($attr_ids as $k => $v) {
        $info=Db::name('attr')->alias('a')->join('__ATTR_TYPE__ b','a.type_id=b.id')->field('a.aname,b.name')->where('a.id',$v)->find();
        //dump($info);
        $attrs[$k]=$info['name'].':'.$info['aname'];
    }
    $attrs=implode('  ',$attrs);
    //dump($attrs);
    return $attrs;
}

function getAttrs($attr_ids){
    $attr_ids=explode(',',$attr_ids);
    $attrs=[];
    foreach ($attr_ids as $k => $v) {
        $attrs[$k]=Db::name('attr')->where('id',$v)->value('aname');
    }
    $attrs=implode(';',$attrs);
    //dump($attrs);
    return $attrs;
}

//curl get请求
function getJson($url){
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $output = curl_exec($ch);
    curl_close($ch);
    return json_decode($output, true);
}

//利用此框架的方法将图片上传到admin_attachement数据表
/*
$uid：用户id
$file:表单上传图片的name值
$module:代表哪个模块上传的图片
 */
function upOneimg($uid, $file, $size = 11548484, $path = 'uploads/apifile',$module='api'){
        $file = request()->file($file);
        //dump($file);
        if (empty($file)) {
            $data['code'] = '201';
            $data['msg'] = '请选择文件';
            return $data;
        }
        $size = 11548484;
        $path = $path;
        $env=new \think\facade\Env;
        $info = $file->move($env::get('root_path') . '/public' . $path . '/');
        if ($info) {
            // 缩略图路径
            $thumb_path_name = '';
            // 图片宽度
            $img_width = '';
            // 图片高度
            $img_height = '';
            // $img = Image::open($info);
            $img_width = '';
            $img_height = '';
            // 水印功能
            // 获取附件信息
            $file_info = [
                'uid' => $uid,
                'name' => $file->getInfo('name'),
                'mime' => $file->getInfo('type'),
                'path' => str_replace('\\', '/', $path. '/' . str_replace('\\', '/', $info->getSaveName())),
                'ext' => $info->getExtension(),
                'size' => $info->getSize(),
                'md5' => $info->hash('md5'),
                'sha1' => $info->hash('sha1'),
                'thumb' => $thumb_path_name,
                'module' => $module,
                'width' => $img_width,
                'height' => $img_height,
            ];
            $AttachmentModel=new \app\admin\model\Attachment;
            if ($file_add = $AttachmentModel::create($file_info)) {
            	//dump($file_add);
                $data['code'] = '200';
                //$data['msg'] = $file_add['->getLastInsID()'];
                $data['msg']='上传成功';
                $data['data']['imgid']=$file_add['id'];
                $data['data']['path']=$file_add['path'];
                return $data;
            }
        }
        $data['code'] = '201';
        $data['msg'] = $file->getError();
        return $data;
}

 //多张图上传
function upMultipleimg($uid, $file, $size = 11548484, $path = 'uploads/apifile',$module='api'){
    $files = request()->file($file);
    //dump($files);die;
    if (empty($files)) {
        $data['code'] = '201';
        $data['msg'] = '请选择文件';
        return $data;
    }
    foreach($files as $k=>$file){
    	$size = 11548484;
        $path = $path;
        $env=new \think\facade\Env;
        $info = $file->move($env::get('root_path') . '/public' . $path . '/');
        if ($info) {
            // 缩略图路径
            $thumb_path_name = '';
            // 图片宽度
            $img_width = '';
            // 图片高度
            $img_height = '';
            // $img = Image::open($info);
            $img_width = '';
            $img_height = '';
            // 水印功能
            // 获取附件信息
            $file_info = [
                'uid' => $uid,
                'name' => $file->getInfo('name'),
                'mime' => $file->getInfo('type'),
                'path' => str_replace('\\', '/', $path . '/' . str_replace('\\', '/', $info->getSaveName())),
                'ext' => $info->getExtension(),
                'size' => $info->getSize(),
                'md5' => $info->hash('md5'),
                'sha1' => $info->hash('sha1'),
                'thumb' => $thumb_path_name,
                'module' => $module,
                'width' => $img_width,
                'height' => $img_height,
            ];
            $AttachmentModel=new \app\admin\model\Attachment;
            if (!$file_add = $AttachmentModel::create($file_info)) {
            	//dump($file_add);
                //$data['msg'] = $file_add['->getLastInsID()'];
                $data['code'] = '202';
				$data['msg']='上传失败';
            }else{
                $data['code'] = '200';
                $data['msg']='上传成功';
                $data['imgid'][$k]=$file_add['id'];
            }
   		}else{
   			$data['code'] = '202';
	        $data['msg'] = $file->getError();
   		}
    }
    return $data;
}

//生成$num位的随机数
function randcode($num){
    $code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $rand = $code[rand(0,25)]
        .strtoupper(dechex(date('m'))) //dechex()将10进制变成16进制
        .date('d')
        .substr(time(),-5)
        .substr(microtime(),2,5)
        .sprintf('%02d',rand(0,99));
    for(
        $a = md5( $rand, true ),
        $s = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ',
        $d = '',
        $f = 0;
        $f < $num;
        $g = ord( $a[ $f ] ),//ord() 函数返回字符串的首个字符的 ASCII 值
        $d .= $s[ ( $g ^ ord( $a[ $f + 8 ] ) ) - $g & 0x1F ],
        $f++
    );
    return $d;
}

//rsa 私钥解密
function pri_rsa($password){
    //私钥
    $pri_key = "-----BEGIN PRIVATE KEY-----
MIICeAIBADANBgkqhkiG9w0BAQEFAASCAmIwggJeAgEAAoGBAK7ROXwxY/ChypSU
/gUWgJP+PqOi4AyVt2I6Zl+rYENg2Ah0dDjl08jMXs42evAkCasqHG4pIsQEZ12v
I6Xj6VMbqRfB/XO8Uwmvtcg86Qb+HxjgAa/JJMOY3HOHrgRtt9QSTQQGVxtyItLH
UnPVB5SVATMP0EeaM5YMDVROUIA5AgMBAAECgYAvQxVdhCTWy4bvQJCkY38Dg7r/
lmsoO9nGTq+ascRmsun07zb0ov3szYPcEFKQVc3fXpUtGyXxBJfFdjIXCVTs1l6f
nQih6H2So+9jm7Zr3eXOVYjmEkWR0WCRNiMwa48XZRykea7KUSGnTvLKv/uUTFxP
RVGXAKQV/NSRn2KqAQJBAOOMk8K3vsfxeQH6riTo4j73cn3hc2VqC5orr3M78H8Z
mRK6BMoGNPwZ2A5iUHHPsMbOSt7u5nKe8Vs1hTqObpkCQQDErMymS1tqOzPIBuB8
XCh/rCtDEpK/DLLdzMmllx2wQ9rw86KWKvy2iLLRTAG2D84w9ekQL20V928D+NxX
dcKhAkEA4eEKTKBZoeDyXiSZ+cmzzQ2VeZ/zDRjXq5Lx91HoykJ+0TgWyPSgZCDD
eIPflxq0QKVHbUV5PQ7KR+A5AIejAQJBAK5L9ZHqdrlOfjVm4stTYRDEpBJtA2AN
APdP5eS6Z7UubXnccNpkflHGE7MoiNuwZis9w650WVh+UARVJ/DajAECQQDEBV7A
cusNgdbGqkp9fO1os85iQ1eE07IP/W04KuI41OzIgcNz+W0HnnVid/toykqRSakM
fq4mnztrwANzE4Zp
-----END PRIVATE KEY-----";
    $b = trim($password);//加密过的密码数据
    $c = '';//解密明文
    openssl_private_decrypt(base64_decode($b),$c,$pri_key);//私钥解密，解密前数据需要执行base64_decode
//        dump($c);die;
    return $c;
}

//rsa 公钥加密
/*
    $password 要加密的字符串
*/
function pub_rsa($password){
    //公钥
    $pub_key="-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCu0Tl8MWPwocqUlP4FFoCT/j6j
ouAMlbdiOmZfq2BDYNgIdHQ45dPIzF7ONnrwJAmrKhxuKSLEBGddryOl4+lTG6kX
wf1zvFMJr7XIPOkG/h8Y4AGvySTDmNxzh64EbbfUEk0EBlcbciLSx1Jz1QeUlQEz
D9BHmjOWDA1UTlCAOQIDAQAB
-----END PUBLIC KEY-----
";
    $e=''; //加密后的字符串
    openssl_public_encrypt($password,$e,$pub_key);
    $e=base64_encode($e);  //加密后数据需要执行base64_encode，不然乱码
    return $e;
}


function FromXml($xml)
{
    if(!$xml){
        echo "xml数据异常！";
    }
    //将XML转为array
    //禁止引用外部xml实体
    libxml_disable_entity_loader(true);
    $data = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
    return $data;
}

function getHeader($name=''){
    $header = [];
    if (function_exists('apache_request_headers') && $result = apache_request_headers()) {
        $header = $result;
    } else {
        $name = strtolower($name);
        $server = $_SERVER;
        foreach ($server as $key => $val) {
            if (0 === strpos($key, 'HTTP_')) {
                $key          = str_replace('_', '-', strtolower(substr($key, 5)));
                $header[$key] = $val;
            }
        }
        if (isset($server['CONTENT_TYPE'])) {
            $header['content-type'] = $server['CONTENT_TYPE'];
        }
        if (isset($server['CONTENT_LENGTH'])) {
            $header['content-length'] = $server['CONTENT_LENGTH'];
        }
    }
    return $header[$name]?$header[$name]:null;
}